package org.kzwl.service.web.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.emoji.EmojiUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kzwl.comm.advice.BizException;
import org.kzwl.comm.advice.Consts;
import org.kzwl.comm.pojo.ResponseData;
import org.kzwl.comm.pojo.bo.QueryThearBO;
import org.kzwl.comm.pojo.bo.SaveThearBO;
import org.kzwl.comm.pojo.bo.ThearApprovalBO;
import org.kzwl.comm.pojo.bo.ThearAuditBO;
import org.kzwl.comm.pojo.bo.thear.AddThearBO;
import org.kzwl.comm.pojo.bo.thear.ThearDetails;
import org.kzwl.comm.pojo.bo.thear.ThearQueryBasicBO;
import org.kzwl.comm.pojo.dto.ThearApprovalDTO;
import org.kzwl.comm.pojo.dto.heritage.QueryDetailsDTO;
import org.kzwl.comm.pojo.dto.thear.ThearDetailsDTO;
import org.kzwl.comm.utils.MyUtils;
import org.kzwl.entity.app.User;
import org.kzwl.entity.web.Admin;
import org.kzwl.entity.web.CuHeritage;
import org.kzwl.entity.web.Thear;
import org.kzwl.mapper.app.UserMapper;
import org.kzwl.mapper.web.AdminMapper;
import org.kzwl.mapper.web.ThearMapper;

import org.kzwl.service.web.ThearService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class ThearServiceImpl extends ServiceImpl<ThearMapper, Thear> implements ThearService {

    @Resource
    private ThearMapper thearMapper;

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseData<Void> saveOne(SaveThearBO saveThearBO) {
        if ("".equals(saveThearBO.getCuThearTitle())) {
            throw new BizException("标题不能为空");
        }
        if ("".equals(saveThearBO.getCuThearCenter())) {
            throw new BizException("内容不能为空");
        }
        if (saveThearBO.getCuThearCatId() == null) {
            throw new BizException("分类不能为空");
        }

        if (saveThearBO.getCuTownId() == null) {
            throw new BizException("分镇ID不能为空");
        }
        Thear thear = new Thear();
        BeanUtils.copyProperties(saveThearBO, thear);
        thear.setCuParentOne(2);
        thear.setCuThearMessage("管理员");
        this.baseMapper.insert(thear);
        return new ResponseData<>();
    }

    @Override
    public ResponseData<IPage<Thear>> queryPage(QueryThearBO queryThearBO) {
        LambdaQueryWrapper<Thear> thearLambdaQueryWrapper = new LambdaQueryWrapper<Thear>();
        thearLambdaQueryWrapper.eq(Thear::getCuTownId, queryThearBO.getCuTownId())
                .eq(queryThearBO.getCuThearCatId() != null,Thear::getCuThearCatId,queryThearBO.getCuThearCatId());
        Page<Thear> thearPage = this.baseMapper.selectPage(new Page<>(queryThearBO.getCurrent(), queryThearBO.getSize()),thearLambdaQueryWrapper );
        return new ResponseData<>(thearPage);
    }

    @Override
    public ResponseData<Thear> queryOne(Long Id) {

        Thear thear = this.baseMapper.selectById(Id);
        if (thear == null) {
            throw new BizException("信息不存在");
        }
        return new ResponseData<>(thear);
    }

    @Override
    public ResponseData<Void> deleteId(Long Id) {
        Thear thear = this.baseMapper.selectById(Id);
        if (thear == null) {
            throw new BizException("信息不存在");
        }
        this.baseMapper.deleteById(Id);
        return new ResponseData<>();
    }

    @Override
    public ResponseData<Void> updateId(Thear thear) {
        Thear selectById = this.baseMapper.selectById(thear.getCuThearId());
        if (selectById == null) {
            throw new BizException("信息不存在");
        }
        this.baseMapper.updateById(thear);
        return new ResponseData<>();
    }

    //region web接口-基础查询
    @Override
    public IPage<Thear> queryBasic(ThearQueryBasicBO bo) {
        QueryWrapper<Thear> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(bo.getCuThearCatId() != null, Thear::getCuThearCatId, bo.getCuThearCatId())
                .eq(Thear::getCuParentOne,2)
                .eq(bo.getCuTownId()!=null,Thear::getCuTownId,bo.getCuTownId())
                .orderByDesc(Thear::getCuThearDate);
        IPage<Thear> page = new Page<>();
        page.setCurrent(bo.getCurrent());
        page.setSize(bo.getSize());
        page = thearMapper.selectPage(page, queryWrapper);
        return page;
    }
    //endregion

    //region web接口-查询风采详细
    @Override
    public ThearDetailsDTO queryDetails(ThearDetails bo) {
        Thear thear = thearMapper.selectById(bo.getCuThearId());
        if (thear == null) {
            throw new BizException("未找到相关信息");
        }
        ThearDetailsDTO dto = new ThearDetailsDTO();
        BeanUtils.copyProperties(thear, dto);

        //region 查询上一条
        QueryWrapper<Thear> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().gt(Thear::getCuThearId, dto.getCuThearId()).eq(Thear::getCuParentOne,2).last(" limit 1");
        Thear next = thearMapper.selectOne(queryWrapper);
        if (next != null) {
            ThearDetailsDTO.ThearItem item = new ThearDetailsDTO.ThearItem();
            item.setCuThearId(next.getCuThearId());
            item.setCuThearTitle(next.getCuThearTitle());
            dto.setNext(item);
        }

        queryWrapper.clear();
        queryWrapper.lambda().lt(Thear::getCuThearId, bo.getCuThearId()).eq(Thear::getCuParentOne,2).orderByDesc(Thear::getCuThearId).last(" limit 1");
        Thear previous = thearMapper.selectOne(queryWrapper);
        if (previous != null) {
            ThearDetailsDTO.ThearItem item = new ThearDetailsDTO.ThearItem();
            item.setCuThearId(previous.getCuThearId());
            item.setCuThearTitle(previous.getCuThearTitle());
            dto.setPrevious(item);
        }
        //endregion
        if (dto.getCuUserId() != null && dto.getCuUserId() != 0) {
            User user = userMapper.selectById(dto.getCuUserId());
            dto.setAuthorName(user.getCuUsername());
        } else {
            dto.setAuthorName("蒲县文化中心");
        }
        return dto;
    }
    //endregion

    //region 风采展示发布
    @Override
    public void addThear(AddThearBO bo) {
        Thear thear = new Thear();
        BeanUtils.copyProperties(bo, thear);
        thearMapper.insert(thear);
    }
    //endregion


    @Override
    public ResponseData<IPage<ThearApprovalDTO>> queryApproval(ThearApprovalBO thearApprovalBO) {

        Admin admin = this.adminMapper.selectById(thearApprovalBO.getCuAdminId());
        if (admin == null) {
            throw new BizException("管理员不存在");
        }
        IPage<ThearApprovalDTO> iPage = new Page<>(thearApprovalBO.getCurrent(), thearApprovalBO.getSize());
        IPage<ThearApprovalDTO> theatPage = this.thearMapper.queryAuth(iPage, thearApprovalBO);
        theatPage.getRecords().forEach(item -> {
            User user = this.userMapper.selectById(item.getCuUserId());
            if (ObjectUtil.isNotNull(user)) {
                item.setCuUsername(user.getCuUsername());
            } else {
                item.setCuUsername("管理员:" + admin.getCuAdminUsername());
            }

        });
        return new ResponseData<>(theatPage);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseData<Void> thearAudit(ThearAuditBO thearAuditBO) {
        Admin admin = this.adminMapper.selectById(thearAuditBO.getCuAdminId());
        if (ObjectUtil.isNull(admin)) {
            throw new BizException("管理员不存在");
        }
        if (admin.getCuParentId() != thearAuditBO.getCuParentId()) {
            throw new BizException("信息错误");
        }
        Thear thear = new Thear();
        Thear selectById = this.baseMapper.selectById(thearAuditBO.getCuThearId());
        if (thearAuditBO.getCuParentId() == 0) {
            if (selectById.getCuParentOne() >= 1) {
                throw new BizException("此信息已经进行过操作");
            }
        } else if (thearAuditBO.getCuParentId() == 1) {
            if (selectById.getCuParentOne() >= 2) {
                throw new BizException("此信息已经进行过操作");
            }
        }
        thear.setCuThearId(thearAuditBO.getCuThearId());
        thear.setCuParentOne(thearAuditBO.getCuParentOne());
        this.updateId(thear);

        Thear byId = this.baseMapper.selectById(thearAuditBO.getCuThearId());
        if (ObjectUtil.isNull(byId))
        {
            throw new BizException("风采信息错误");
        }
        User user = this.userMapper.selectById(byId.getCuUserId());
        if (ObjectUtil.isNull(user))
        {
            throw new BizException("用户信息错误");
        }
        if (thearAuditBO.getCuParentOne()==4 || thearAuditBO.getCuParentOne()==3){
            MyUtils.sendSms(user.getCuUserPhone(),"{" +
                    "\"name\":\"" + user.getCuUsername() + "\"," +
                    "\"title\":\"" + byId.getCuThearTitle() +"\"," +
                    "\"state\":\"未通过\"" +
                    "}", Consts.AliYun.SMSTHEAR);
        }else if (thearAuditBO.getCuParentOne()==2){
            String param = "{" +
                    "\"name\":\"" + user.getCuUsername() + "\"," +
                    "\"title\":\"" + byId.getCuThearTitle() +"\"," +
                    "\"state\":\"已通过\"" +
                    "}";
            System.out.println(param);
            MyUtils.sendSms(user.getCuUserPhone(),param, Consts.AliYun.SMSTHEAR);
        }
        return new ResponseData<>();
    }
}
